import { finishMsg } from '@/hooks/usePageVariable';
import { formatTreeData, getTreeDataCheckKeys, getTreeDataKeys } from '@/pages/system/role/util';
import { getDictByCode } from '@/services/system/dict';
import { getTreeList } from '@/services/system/menu';
import { getRoleMenuList, setRoleMenuList } from '@/services/system/role';
import { StrUtil } from '@/util/msg';
import { Modal, Tree, TreeDataNode, TreeProps } from 'antd';
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import styles from './style.module.less';

interface CaptchaInputProps {
  setRoleModel: Dispatch<SetStateAction<boolean>>;
  roleModel: boolean;
  id: string;
}

const RoleForm = (props: CaptchaInputProps) => {
  const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    console.log('checkedKeysValue', checkedKeysValue);
    setCheckedKeys(checkedKeysValue as React.Key[]);
  };

  const closeRoleModel = (open: boolean) => {
    if (open) {
      finishMsg({
        call: async () => {
          const data: { [key: string]: string } = {};
          for (let checkedKey of checkedKeys) {
            let strings = checkedKey.toString().split(StrUtil.DASHED);
            if (strings[2] === '0') continue;
            if (strings.length > 3) {
              data[strings[2]] = data[strings[2]]
                ? `${data[strings[2]]}${StrUtil.COMMIT}${strings[3]}`
                : strings[3];
            } else {
              if (!data[strings[2]]) {
                data[strings[2]] = '';
              }
            }
          }
          const dataList = Object.keys(data).map((key) => {
            return {
              menuCode: key,
              actionType: data[key],
            };
          });
          await setRoleMenuList({
            roleId: props.id,
            dataList: JSON.stringify(dataList),
          });
        },
      }).then();
    }
    props.setRoleModel(false);
  };

  const getInitData = async () => {
    const [ret, dict, menuList] = await Promise.all([
      getTreeList(),
      getDictByCode('actionType'),
      getRoleMenuList(props.id),
    ]);
    dict.data = dict.data.map((c) => {
      c.code = c.value;
      return c;
    });
    const data = formatTreeData(ret.data, dict.data);
    setTreeData(data);
    const keyData = getTreeDataKeys(data, 'value');
    setExpandedKeys(keyData);
    const list = getTreeDataCheckKeys(data, menuList.data);
    setCheckedKeys(list);
  };

  useEffect(() => {
    getInitData().then(() => {});
  }, []); // 空数组意味着这个effect只在组件挂载时执行一次

  return (
    <Modal
      title="分配权限"
      open={props.roleModel}
      onOk={() => closeRoleModel(true)}
      onCancel={() => closeRoleModel(false)}
      width="80%"
    >
      <Tree
        className={styles.roleForm}
        checkable
        expandedKeys={expandedKeys}
        autoExpandParent={true}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        treeData={treeData}
        selectable={false}
        fieldNames={{
          key: 'value',
        }}
      />
    </Modal>
  );
};
export default RoleForm;
